package com.css.fxfzypg.modules.resultManagement.reportReview.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.baseData.entity.HisPrEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.HistoryUploadReport;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.ReviewRecord;
import com.css.fxfzypg.modules.resultManagement.reportReview.repository.ReportReviewRepository;
import com.css.fxfzypg.modules.resultManagement.reportReview.vo.ReportReviewVo;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class ReportReviewRepositoryImpl implements ReportReviewRepository {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Resource
    SysAreaService sysAreaService;

    @Resource
    SysRoleService sysRoleService;

    @Resource
    SUserService sUserService;


    @Override
    public Map<String, Object> getPage(ReportReviewVo reportReviewVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select t2.id taskId,t2.task_num,t2.task_name,t2.task_manager,t1.id reportId,t1.user_upload_simple_report_name,t1.user_upload_minute_report_name from ypg_preassess_task_report t1 LEFT JOIN ypg_preassess_task t2 on t1.id = t2.report_id");
        StringBuilder whereSql = new StringBuilder(" where t2.del_flag = '0'  and t1.report_status = '3' ");
        int firstIndex=(curPage-1) * pageSize;
        StringBuilder str=new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for(Map roleMap:roleMaps){
            str.append(roleMap.get("roleCode")+",");
        }
        String roles = str.toString();
        if(!roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)){
            whereSql.append(" and t2.create_user = '"+userId+"'");
        }else if(roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)){
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if(!PlatformObjectUtils.isEmpty(areaNameByAreaId)){
                whereSql.append(" and t2.task_district like '%"+areaNameByAreaId+"%'");
            }
        }

        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getTaskNum())){
            whereSql.append(" and t2.task_num like '%"+reportReviewVo.getTaskNum()+"%'");
        }
        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getTaskName())){
            whereSql.append(" and t2.task_name like '%"+reportReviewVo.getTaskName()+"%'");
        }
        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getTaskManager())){
            whereSql.append(" and t2.task_manager like '%"+reportReviewVo.getTaskManager()+"%'");
        }

        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getProvince()) || !PlatformObjectUtils.isEmpty(reportReviewVo.getCity()) || !PlatformObjectUtils.isEmpty(reportReviewVo.getCounty())){
            if(!PlatformObjectUtils.isEmpty(reportReviewVo.getProvince())){
                whereSql.append(" and t2.task_district like '%"+ reportReviewVo.getProvince() +"%'");
            }
            if(!PlatformObjectUtils.isEmpty(reportReviewVo.getCity())){
                whereSql.append(" and t2.task_district like '%"+ reportReviewVo.getCity() +"%'");
            }
            if(!PlatformObjectUtils.isEmpty(reportReviewVo.getCounty())){
                whereSql.append(" and t2.task_district like '%"+ reportReviewVo.getCounty() +"%'");
            }
        }
        StringBuilder orderSql = new StringBuilder(" order by t1.report_check_time desc ");
        StringBuilder limitSql = new StringBuilder(" limit "+ pageSize +" offset "+ firstIndex);
        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(ReportReviewVo.class)).size();
        String sqlWhole = sql.append(limitSql).toString();
        List<ReportReviewVo> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(ReportReviewVo.class));
        Map<String,Object> map=new HashMap();
        map.put("total",total);
        map.put("rows",list);
        return map;
    }

    @Override
    public Boolean review(String reportStatus, String reviewStatus, String reportId) {
        String sql = "update ypg_preassess_task_report set  report_status = ?,review_status=? where id = ?";
        return jdbcTemplate.update(sql, reportStatus, reviewStatus, reportId) > 0 ;
    }

    @Override
    public Boolean saveHisPr(HisPrEntity hisPrEntity) {
    String sql ="insert into data_his_pr values(:id,:dhpYear,:dhpTaskNum,:dhpTaskName,:dhpEarthquakeNum,:dhpEpicenterLongitude,:dhpEpicenterLatitude,:dhpLocation," +
            ":dhpMagnitude,:dhpDiArea,:dhpDiPeople,:dhpDiGdp,:dhpEsDeath,:dhpEsInjured,:dhpDiEcLosses,:dhpEsResNumber,:dhpNeedEmeAssi,:dhpProResForce,:dhpCivRelEfforts,:dhpOtherForces," +
            ":dhpEsTentsNum,:dhpEsStretcherNum,:dhpEsQuiltNum,:dhpEsFoodNum,:dhpEsWaterNum,:dhpEsToiletNum,:dhpEsBathroomNum,:dhpEsStaffNum,:dhpEsDoctorNum,:dhpEsNurseNum,:dhpEsPsyDoctorNum," +
            ":dhpEsWardNum,:dhpEsBedNum,:dhpEsPlasmaNum,:provinceId,:delFlag,:dhpCreateUser,:dhpCreateTime,:dhpUpdateUser,:dhpUpdateTime) ";
    SqlParameterSource source = new BeanPropertySqlParameterSource(hisPrEntity);
    return namedParameterJdbcTemplate.update(sql, source)>0;
    }

   /* @Override
    public Boolean updateReportStatusById(String reportStatus, String reviewStatus, String reportId) {
        String sql = "update ypg_preassess_task_report set report_status = ?,review_status = ? where id = ?";
        return jdbcTemplate.update(sql, reportStatus, reviewStatus, reportId) > 0 ;
    }*/

    @Override
    public Boolean saveReviewRecord(ReviewRecord reviewRecord) {
        String sql ="insert into ypg_preassess_task_report_record values(:id,:reportId,:reviewStatus,:reviewOpinion,:reviewTime,:userUploadSimpleReportName,:localUserUploadSimpleReportName,:userUploadMinuteReportName,:localUserUploadMinuteReportName,:reportPath) ";
        SqlParameterSource source = new BeanPropertySqlParameterSource(reviewRecord);
        return namedParameterJdbcTemplate.update(sql, source)>0;
    }

    @Override
    public Map<String, Object> getReviewRecordPage(ReportReviewVo reportReviewVo, int curPage, int pageSize) {
         StringBuilder sql = new StringBuilder("select t2.id taskId,t2.task_num,t2.task_name,t2.task_manager,t1.id reportId,t3.user_upload_simple_report_name,t3.user_upload_minute_report_name,t3.review_status,t3.review_opinion,t3.review_time " +
                "from ypg_preassess_task_report_record t3  LEFT JOIN ypg_preassess_task_report t1 on t3.report_id = t1.id LEFT JOIN ypg_preassess_task t2 on t1.id = t2.report_id ");
        StringBuilder whereSql = new StringBuilder(" where t2.del_flag = '0' ");
        int firstIndex=(curPage-1) * pageSize;
        StringBuilder str=new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for(Map roleMap:roleMaps){
            str.append(roleMap.get("roleCode")+",");
        }
        String roles = str.toString();
        if(!roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)){
            whereSql.append(" and t2.create_user = '"+userId+"'");
        }else if(roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)){
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if(!PlatformObjectUtils.isEmpty(areaNameByAreaId)){
                whereSql.append(" and t2.task_district like '%"+areaNameByAreaId+"%'");
            }
        }

        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getTaskNum())){
            whereSql.append(" and t2.task_num like '%"+reportReviewVo.getTaskNum()+"%'");
        }
        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getTaskName())){
            whereSql.append(" and t2.task_name like '%"+reportReviewVo.getTaskName()+"%'");
        }
        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getTaskManager())){
            whereSql.append(" and t2.task_manager like '%"+reportReviewVo.getTaskManager()+"%'");
        }
        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getReviewStatus())){
            whereSql.append(" and t1.review_status = '"+reportReviewVo.getReviewStatus()+ "'");
        }
        if(!PlatformObjectUtils.isEmpty(reportReviewVo.getProvince()) || !PlatformObjectUtils.isEmpty(reportReviewVo.getCity()) || !PlatformObjectUtils.isEmpty(reportReviewVo.getCounty())){
            if(!PlatformObjectUtils.isEmpty(reportReviewVo.getProvince())){
                whereSql.append(" and t2.task_district like '%"+ reportReviewVo.getProvince() +"%'");
            }
            if(!PlatformObjectUtils.isEmpty(reportReviewVo.getCity())){
                whereSql.append(" and t2.task_district like '%"+ reportReviewVo.getCity() +"%'");
            }
            if(!PlatformObjectUtils.isEmpty(reportReviewVo.getCounty())){
                whereSql.append(" and t2.task_district like '%"+ reportReviewVo.getCounty() +"%'");
            }
        }
        StringBuilder orderSql = new StringBuilder(" order by t3.review_time desc ");
        StringBuilder limitSql = new StringBuilder(" limit "+ pageSize +" offset "+ firstIndex);
        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(ReportReviewVo.class)).size();
        String sqlWhole = sql.append(limitSql).toString();
        List<ReportReviewVo> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(ReportReviewVo.class));
        Map<String,Object> map=new HashMap();
        map.put("total",total);
        map.put("rows",list);
        return map;
    }

    @Override
    public PreAssessTaskEntity getTaskIdByReportId(String reportId) {
        String sql="select * from ypg_preassess_task where report_id = ? ";
        PreAssessTaskEntity preAssessTaskEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class), reportId);
        return preAssessTaskEntity;
    }


}
